'''
calculate the passager
'''
import cv2
import numpy as np
import time

MAN_COUNT = 0 # people number（全局变量）

# 人脸识别训练数据集
bodyCascade = cv2.CascadeClassifier('/home/pi/opencv_build/opencv/data/haarcascades/haarcascade_frontalface_default.xml') 
# upper body detect Classifier
#bodyCascade = cv2.CascadeClassifier('/home/pi/opencv_build/opencv/data/haarcascades/haarcascade_upperbody.xml')  


# 用于后台线程长时间运行，获取人脸识别的人数，保存到全局变量中
# get people number and write into MAN_COUNT
def camera():
    print("[numCalculate.py]: OpenCV Version:{}".format(cv2.__version__))
    cap = cv2.VideoCapture(0)  # 0: use CSI camera,1：use USB camera
    cap.set(3,480) # set Width
    cap.set(4,360) # set Height
    if(not cap.isOpened()):
        print("[camera.py:cam]:can't open this camera")

    while(True): 
        # get body Coordinate and Image with rectangle around body
        bodys, img = detection(cap, bodyCascade)
        # calcute man number
        global MAN_COUNT
        MAN_COUNT = len(bodys)
        cv2.putText(img,'num: '+str(MAN_COUNT),(5,40), cv2.FONT_ITALIC,1,(0,0,255),1)
        # show image
        cv2.imshow('upperbody',img)
        # press [q] to quit
        if (cv2.waitKey(1)) == ord('q'):
            cap.release()
            break
        # wait for 1s
        time.sleep(1)
    # Release resource
    cv2.destroyAllWindows()

# 旧版本未精简的camera代码
def camera_show():
    print("[numCalculate.py]: OpenCV Version:{}".format(cv2.__version__))
    cap = cv2.VideoCapture(0)  # 0: use CSI camera,1：use USB camera
    cap.set(3,480) # set Width
    cap.set(4,360) # set Height
    #lineHeight = 180
    #lineWidth = 470
    if(not cap.isOpened()):
        print("[camera.py:cam]:can't open this camera")

    while(True): 
        # get body Coordinate and Image with rectangle around body
        bodys, img = detection(cap, bodyCascade)

        # draw a dividing line
        #cv2.line(img, (0, lineHeight), (lineWidth, lineHeight), (0,255,0), 1)
        #cv2.line(img, (0, lineHeight+40), (lineWidth, lineHeight+40), (0,255,0), 1)

        # calcute man number
        global MAN_COUNT
        MAN_COUNT = len(bodys)
        #print(MAN_COUNT)
        cv2.putText(img,'num: '+str(MAN_COUNT),(5,40), cv2.FONT_ITALIC,1,(0,0,255),1)

        # show image
        cv2.imshow('upperbody',img)
        # press [q] to quit
        if (cv2.waitKey(1)) == ord('q'):
            cap.release()
            break

        # wait for 2s
        time.sleep(1)

    # Release resource
    cv2.destroyAllWindows()




def detection(cap, bodyCascade):
    # @input: cap from camera()
    # @output: body(x,y,w,h) img
    ret, img = cap.read() 
    grayimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # change to gray image

    # get the body area's [x,y,w,h]
    bodys = bodyCascade.detectMultiScale(
        grayimg,     
        scaleFactor=1.2,
        minNeighbors=3,     
        minSize=(20, 20)
    )
    # draw a rectangle around body
    for (x,y,w,h) in bodys:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

    return bodys, img


def get_people_count():
    return MAN_COUNT

def get_people_count_once():
    # get people number and write into MAN_COUNT
    cap = cv2.VideoCapture(0)  # 0: use CSI camera,1：use USB camera
    cap.set(3,1280) # set Width
    cap.set(4,720) # set Height
    #lineHeight = 180
    #lineWidth = 470
    if(not cap.isOpened()):
        print("[camera.py:cam]:can't open this camera")

    
    # get body Coordinate and Image with rectangle around body
    bodys, img = detection(cap, bodyCascade)

    # draw a dividing line
    #cv2.line(img, (0, lineHeight), (lineWidth, lineHeight), (0,255,0), 1)
    #cv2.line(img, (0, lineHeight+40), (lineWidth, lineHeight+40), (0,255,0), 1)

    return len(bodys)



if __name__ == "__main__":
    count = 0

    # while(count < 10):
    #     people = get_people_count_once()
    #     print("the number: ", people)
    #     print(count)
    #     time.sleep(1)
    #     count = count +1
    camera_show()


